<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档上传 - RDK X5智能办公系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            padding-top: 56px;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            background-color: #f8f9fa;
        }
        .content {
            flex: 1;
            padding: 2rem 0;
        }
        .footer {
            background-color: #343a40;
            color: #fff;
            padding: 1.5rem 0;
            margin-top: auto;
        }
        .upload-container {
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
            padding: 2rem;
            margin-bottom: 2rem;
        }
        .upload-dropzone {
            border: 2px dashed #0d6efd;
            border-radius: 10px;
            padding: 3rem 2rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .upload-dropzone:hover, .upload-dropzone.dragover {
            background-color: rgba(13, 110, 253, 0.05);
            border-color: #0a58ca;
        }
        .upload-icon {
            font-size: 3rem;
            color: #0d6efd;
            margin-bottom: 1rem;
        }
        .file-list {
            margin-top: 2rem;
        }
        .file-item {
            display: flex;
            align-items: center;
            padding: 0.75rem 1rem;
            border-bottom: 1px solid #dee2e6;
            transition: background-color 0.3s;
        }
        .file-item:hover {
            background-color: #f8f9fa;
        }
        .file-item:last-child {
            border-bottom: none;
        }
        .file-icon {
            font-size: 1.5rem;
            margin-right: 1rem;
            color: #dc3545;
        }
        .file-info {
            flex-grow: 1;
        }
        .file-name {
            font-weight: 500;
            margin-bottom: 0.25rem;
        }
        .file-meta {
            font-size: 0.875rem;
            color: #6c757d;
        }
        .file-actions {
            white-space: nowrap;
        }
        .progress {
            height: 0.5rem;
            border-radius: 0.25rem;
            margin-top: 1rem;
            display: none;
        }
        .upload-status {
            margin-top: 1rem;
            display: none;
        }
        .empty-state {
            text-align: center;
            padding: 2rem 0;
            color: #6c757d;
        }
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top">
        <div class="container">
            <a class="navbar-brand" href="/">RDK X5智能办公系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link active" href="/">文档上传</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/process">文档处理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/download">文件下载</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 内容区 -->
    <div class="container content">
        <div class="row">
            <div class="col-12">
                <h1 class="display-5 mb-4">文档上传中心</h1>
                <p class="lead mb-4">上传您的PDF文件用于后续处理。支持拖拽上传或点击选择文件。</p>
                
                <!-- 上传区域 -->
                <div class="upload-container">
                    <div class="upload-dropzone" id="uploadDropzone">
                        <i class="bi bi-cloud-arrow-up upload-icon"></i>
                        <h4>拖放文件或点击上传</h4>
                        <p class="text-muted">支持上传PDF格式文件</p>
                        <input type="file" id="fileInput" accept=".pdf" style="display: none;">
                    </div>
                    
                    <div class="progress" id="uploadProgress">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                    </div>
                    
                    <div class="alert upload-status" id="uploadStatus"></div>
                </div>
                
                <!-- 已上传文件列表 -->
                <div class="card">
                    <div class="card-header bg-light d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">已上传文件</h5>
                        <button id="refreshFilesBtn" class="btn btn-sm btn-outline-primary">
                            <i class="bi bi-arrow-clockwise"></i> 刷新
                        </button>
                    </div>
                    <div class="card-body p-0">
                        <div id="fileList" class="file-list">
                            <div class="text-center p-3">加载中...</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <div class="text-center">
                <p class="mb-0">RDK X5智能办公系统 &copy; 2025</p>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // DOM元素
            const uploadDropzone = document.getElementById('uploadDropzone');
            const fileInput = document.getElementById('fileInput');
            const uploadProgress = document.getElementById('uploadProgress');
            const progressBar = uploadProgress.querySelector('.progress-bar');
            const uploadStatus = document.getElementById('uploadStatus');
            const fileList = document.getElementById('fileList');
            const refreshFilesBtn = document.getElementById('refreshFilesBtn');
            
            // 点击上传区域触发文件选择
            uploadDropzone.addEventListener('click', function() {
                fileInput.click();
            });
            
            // 拖放事件处理
            uploadDropzone.addEventListener('dragover', function(e) {
                e.preventDefault();
                this.classList.add('dragover');
            });
            
            uploadDropzone.addEventListener('dragleave', function() {
                this.classList.remove('dragover');
            });
            
            uploadDropzone.addEventListener('drop', function(e) {
                e.preventDefault();
                this.classList.remove('dragover');
                
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    handleFileUpload(files[0]);
                }
            });
            
            // 文件选择处理
            fileInput.addEventListener('change', function() {
                if (this.files.length > 0) {
                    handleFileUpload(this.files[0]);
                    // 重置文件输入使同一文件能够再次上传
                    this.value = '';
                }
            });
            
            // 处理文件上传
            function handleFileUpload(file) {
                // 验证文件类型
                if (!file.name.toLowerCase().endsWith('.pdf')) {
                    showUploadStatus('只支持上传PDF文件', 'danger');
                    return;
                }
                
                // 创建FormData对象
                const formData = new FormData();
                formData.append('file', file);
                
                // 显示进度条
                uploadProgress.style.display = 'block';
                progressBar.style.width = '0%';
                uploadStatus.style.display = 'none';
                
                // 发送上传请求
                const xhr = new XMLHttpRequest();
                xhr.open('POST', '/upload');
                
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        const percent = Math.round((e.loaded / e.total) * 100);
                        progressBar.style.width = percent + '%';
                    }
                });
                
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            if (response.success) {
                                showUploadStatus(`文件 ${response.filename} 上传成功`, 'success');
                                loadFileList();
                            } else {
                                showUploadStatus(response.error || '上传失败', 'danger');
                            }
                        } catch (error) {
                            showUploadStatus('解析响应失败', 'danger');
                        }
                    } else {
                        showUploadStatus('上传失败: 服务器错误', 'danger');
                    }
                };
                
                xhr.onerror = function() {
                    showUploadStatus('上传失败: 网络错误', 'danger');
                };
                
                xhr.send(formData);
            }
            
            // 显示上传状态
            function showUploadStatus(message, type) {
                uploadStatus.textContent = message;
                uploadStatus.className = `alert upload-status alert-${type}`;
                uploadStatus.style.display = 'block';
                
                // 3秒后自动隐藏状态
                setTimeout(function() {
                    uploadStatus.style.display = 'none';
                }, 3000);
            }
            
            // 加载文件列表
            function loadFileList() {
                fileList.innerHTML = '<div class="text-center p-3">加载中...</div>';
                
                fetch('/api/files')
                .then(response => response.json())
                .then(data => {
                    if (data.uploads && data.uploads.length > 0) {
                        fileList.innerHTML = '';
                        
                        data.uploads.forEach(file => {
                            const fileItem = document.createElement('div');
                            fileItem.className = 'file-item';
                            fileItem.innerHTML = `
                                <i class="bi bi-file-pdf file-icon"></i>
                                <div class="file-info">
                                    <div class="file-name">${file.name}</div>
                                    <div class="file-meta">${formatFileSize(file.size)} • ${file.modified}</div>
                                </div>
                                <div class="file-actions">
                                    <a href="/api/download-upload/${file.name}" class="btn btn-sm btn-outline-primary me-1">
                                        <i class="bi bi-download"></i> 下载
                                    </a>
                                    <button class="btn btn-sm btn-outline-danger delete-file" data-filename="${file.name}">
                                        <i class="bi bi-trash"></i> 删除
                                    </button>
                                </div>
                            `;
                            
                            fileList.appendChild(fileItem);
                        });
                        
                        // 添加删除事件监听
                        document.querySelectorAll('.delete-file').forEach(button => {
                            button.addEventListener('click', function() {
                                const filename = this.getAttribute('data-filename');
                                deleteFile(filename, this.closest('.file-item'));
                            });
                        });
                    } else {
                        fileList.innerHTML = `
                            <div class="empty-state">
                                <i class="bi bi-file-earmark-x"></i>
                                <h5>暂无上传文件</h5>
                                <p>您可以拖放文件到上方区域或点击上传按钮添加文件</p>
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    fileList.innerHTML = '<div class="text-center p-3 text-danger">加载文件列表失败</div>';
                });
            }
            
            // 删除文件
            function deleteFile(filename, element) {
                if (confirm(`确定要删除文件 ${filename} 吗？`)) {
                    fetch(`/api/delete-upload/${filename}`, {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // 移除文件元素
                            element.remove();
                            
                            // 检查是否还有其他文件
                            if (fileList.childElementCount === 0) {
                                fileList.innerHTML = `
                                    <div class="empty-state">
                                        <i class="bi bi-file-earmark-x"></i>
                                        <h5>暂无上传文件</h5>
                                        <p>您可以拖放文件到上方区域或点击上传按钮添加文件</p>
                                    </div>
                                `;
                            }
                        } else {
                            alert(`删除失败: ${data.error || '未知错误'}`);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('删除请求失败');
                    });
                }
            }
            
            // 刷新文件列表
            refreshFilesBtn.addEventListener('click', loadFileList);
            
            // 格式化文件大小
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
            
            // 初始加载文件列表
            loadFileList();
        });
    </script>
</body>
</html>